/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package guiforms;

import controlers.BasketControler;
import controlers.BuyControler;
import controlers.ChecksControler;
import controlers.MainControler;
import controlers.StoreControler;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import model.Checks;
import model.Product;
import model.ProductPurchase;
import model.Purchase;
import model.Store;

/**
 *
 * @author Tasos
 */
public class BuyProductsScreen extends javax.swing.JFrame {
private String customerID = "";
MainControler ctrl = new MainControler();      //mainControler
StoreControler strctrl = new StoreControler();
DefaultListModel listModelright;
DefaultListModel listModelleft;
DefaultTableModel checklistmodel;
ArrayList<ProductPurchase> basket = new ArrayList<>(); //to kalathi mas
float totalprice;
int points;
String clearStore;
List<Integer> checks2remove = new ArrayList<>();
Purchase purchase = new Purchase(0);
   
    /**
     * Creates new form BuyProductsScreen
     * 
     */
    public BuyProductsScreen() {
    //model kalathiou [display mono, to pragmatiko kalathi einai mia lista]
    listModelright = new DefaultListModel();  
    listModelleft = new DefaultListModel();   //model katalogou proiontwn
    totalprice=0;                             //synolikh timh
    points=0;                                 //pontoi agoras
    //To model ths listas (Jtable) diathesimwn epitagwn
    checklistmodel = new DefaultTableModel(){@Override public boolean isCellEditable(int row, int column) {return false;}};  
    //O voithitikos Controler epitagwn
    ChecksControler cc = new ChecksControler();
    //mia lista pou krata tis epitages
    List<Checks> CheckList = cc.getCustomerChecks(customerID);
    checklistmodel.setColumnIdentifiers(new String[]{"Κωδικός","Ημερ/νία"});
    checklistmodel.setColumnCount(2);
    //eisagwgh epitagwn ston pinaka epiloghs
    for(Checks check : CheckList)
    {
    //An h epitagh einai axrisimopoihth
    if(check.getValid()){
    //provalete
    checklistmodel.addRow(new String[] {check.getCheckid().toString(),check.getDate()});
    }
    }
           
    initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane3 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        buttonGroup1 = new javax.swing.ButtonGroup();
        jSeparator1 = new javax.swing.JSeparator();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jListAvailableProducts = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        jListBasket = new javax.swing.JList();
        jLabel2 = new javax.swing.JLabel();
        btnAddProduct = new javax.swing.JButton();
        btnRemoveBasketProduct = new javax.swing.JButton();
        btnEmptyBasket = new javax.swing.JButton();
        btnCompleteBuy = new javax.swing.JButton();
        btnBuyExit = new javax.swing.JButton();
        jTxtfBuyTotal = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jTxtfPurchasePoints = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jSpinnerProductNum = new javax.swing.JSpinner();
        jComboBoxStores = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane4 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jLabel7 = new javax.swing.JLabel();
        jRadioButtonPickup = new javax.swing.JRadioButton();
        jRadioButtonDelivery = new javax.swing.JRadioButton();
        jLabel8 = new javax.swing.JLabel();
        useCheck = new javax.swing.JButton();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane3.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jTextField1.setEditable(false);
        jTextField1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jTextField1.setText("Αγορα Προιόντων");
        jTextField1.setBorder(null);

        jLabel1.setText("Διαθέσιμα Προιόντα");

        jListAvailableProducts.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jListAvailableProducts.setModel(listModelleft);
        jListAvailableProducts.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        jListAvailableProducts.setVisibleRowCount(15);
        jScrollPane1.setViewportView(jListAvailableProducts);

        jListBasket.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jListBasket.setModel(listModelright);
        jListBasket.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        jListBasket.setVisibleRowCount(15);
        jScrollPane2.setViewportView(jListBasket);

        jLabel2.setText("Καλάθι Αγορών");

        btnAddProduct.setText("Προσθήκη Επιλογής >>");
        btnAddProduct.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddProductActionPerformed(evt);
            }
        });

        btnRemoveBasketProduct.setText("Αφαίρεση Επιλεγμένου");
        btnRemoveBasketProduct.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveBasketProductActionPerformed(evt);
            }
        });

        btnEmptyBasket.setText("Αδειασμα καλαθιου");
        btnEmptyBasket.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEmptyBasketActionPerformed(evt);
            }
        });

        btnCompleteBuy.setText("Ολοκλήρωση Αγορών");
        btnCompleteBuy.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCompleteBuyActionPerformed(evt);
            }
        });

        btnBuyExit.setText("Έξοδος");
        btnBuyExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuyExitActionPerformed(evt);
            }
        });

        jTxtfBuyTotal.setEditable(false);
        jTxtfBuyTotal.setText("0");

        jLabel3.setText("Συνολικό ποσο");

        jTxtfPurchasePoints.setEditable(false);
        jTxtfPurchasePoints.setText("0");

        jLabel4.setText("Πόντοι Αγοράς");

        jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel5.setText("Ποσότητα");

        jSpinnerProductNum.setModel(new javax.swing.SpinnerNumberModel(1, 1, 99, 1));

        jComboBoxStores.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jComboBoxStores.setRenderer(jComboBoxStores.getRenderer());
        jComboBoxStores.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxStoresActionPerformed(evt);
            }
        });
        jComboBoxStores.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jComboBoxStoresFocusGained(evt);
            }
        });

        jLabel6.setText("Επιλογή Καταστήματος");

        jTable2.setModel(checklistmodel);
        jTable2.getTableHeader().setReorderingAllowed(false);
        jScrollPane4.setViewportView(jTable2);
        if (jTable2.getColumnModel().getColumnCount() > 0) {
            jTable2.getColumnModel().getColumn(0).setResizable(false);
            jTable2.getColumnModel().getColumn(1).setResizable(false);
        }

        jLabel7.setText("Επιταγές");

        buttonGroup1.add(jRadioButtonPickup);
        jRadioButtonPickup.setSelected(true);
        jRadioButtonPickup.setText("Παραλαβη απο Κατάστημα");

        buttonGroup1.add(jRadioButtonDelivery);
        jRadioButtonDelivery.setText("Παράδοση στον Χώρο σας");

        jLabel8.setText("Παράδοση Προιοντων:");

        useCheck.setText("Χρήση Επιλεγμένης Επιταγής");
        useCheck.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                useCheckActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(jSeparator1)
                .addGap(20, 20, 20))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(btnAddProduct, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(btnCompleteBuy, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(btnBuyExit, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(jSpinnerProductNum))
                                        .addGap(45, 45, 45)))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jComboBoxStores, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(useCheck)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 43, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnRemoveBasketProduct)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnEmptyBasket, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 308, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(19, 19, 19))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTxtfPurchasePoints, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTxtfBuyTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addGap(69, 69, 69)
                                .addComponent(jLabel3))
                            .addComponent(jLabel2)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel8)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jRadioButtonPickup)
                                    .addComponent(jRadioButtonDelivery))))
                        .addGap(0, 0, Short.MAX_VALUE))))
            .addGroup(layout.createSequentialGroup()
                .addGap(285, 285, 285)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(355, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAddProduct, btnBuyExit, btnCompleteBuy});

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jScrollPane1, jScrollPane2});

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jTxtfBuyTotal, jTxtfPurchasePoints});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(3, 3, 3)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jScrollPane2)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 275, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jSpinnerProductNum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(26, 26, 26)
                        .addComponent(btnAddProduct, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnCompleteBuy, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnBuyExit, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnRemoveBasketProduct)
                    .addComponent(btnEmptyBasket)
                    .addComponent(jLabel6))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(4, 4, 4)
                        .addComponent(jComboBoxStores, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel7)
                        .addGap(2, 2, 2)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(useCheck, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTxtfPurchasePoints, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTxtfBuyTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(36, 36, 36)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jRadioButtonPickup)
                            .addComponent(jLabel8))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jRadioButtonDelivery)))
                .addContainerGap(28, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnAddProduct, btnBuyExit, btnCompleteBuy});

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    //Event handler se periptwsh eisagwghs proiontwn sto kalathi
    private void btnAddProductActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddProductActionPerformed
    //An mono yparxei epilegmeno antikeimeno sthn lista proiontwn
    if(jListAvailableProducts.getSelectedValue()!=null){     
    //pernoume ton titlo toy proiontos
    String selection = jListAvailableProducts.getSelectedValue().toString();
    //kai kanoume extract to ID toy me ton parakatw delimiter [Crude but efficient]
    int selectionID = Integer.parseInt(selection.replaceAll(" .*", ""));
    //Instanciate ton controler tou kalathiou 
    BasketControler bc = new BasketControler();
    //Dimiourgoume[ousiastika fernoume] ena antikeimeno product apo to ID toy
    Product procuct2add = bc.fetchProduct(selectionID);
    //kai ena neo ProductPurchase Obj analoga me thn posothta [timh tou jSpinner] 
    ProductPurchase pp = new ProductPurchase(0,Integer.parseInt(jSpinnerProductNum.getValue().toString()));
    pp.setPurchaseId(purchase);
    pp.setProductId(procuct2add);
    //Topothetoume sto kalathi to ProductPurchase Obj
    basket.add(pp);
    
    //enhmerwnoume thn synolikh timh [gui var]
    totalprice = totalprice + procuct2add.getPrice()*Integer.parseInt(jSpinnerProductNum.getValue().toString());
    //kai toys pontous [gui var]
    points = points + procuct2add.getPoints()*Integer.parseInt(jSpinnerProductNum.getValue().toString());
    //kai emfanizoume to epilegmeno proion sthn deksia lista
    listModelright.addElement(bc.fetchProduct(selectionID).getProductId() + " - [" +jSpinnerProductNum.getValue().toString() + " Τεμάχια] " + bc.fetchProduct(selectionID).getName());
    //enhmerwnoume timh kai pontous [gui display from var]
    jTxtfBuyTotal.setText(""+totalprice);
    jTxtfPurchasePoints.setText(""+points);
    //apenergopoioume thn epilogh katasthmatos afou h paragelia exei ksekinisei
    if (!listModelright.isEmpty())
    {
    jComboBoxStores.setEnabled(false);
    }  
    //energopoioume to koumpi oloklhrwshs agorwn
    if(totalprice>=0){
    btnCompleteBuy.setEnabled(true);}   
    }
    }//GEN-LAST:event_btnAddProductActionPerformed

    
    //event handler aferaishs proiontwn apo to kalathi
    private void btnRemoveBasketProductActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveBasketProductActionPerformed
    //efoson yparxei proion sto kalathi
    if(jListBasket.getSelectedValue()!=null){
    //pernoume thn perigrafh toy kai eksagoume to ID kai to index [crudeness again....]
    String selection = jListBasket.getSelectedValue().toString();
    int selectionIndex =jListBasket.getSelectedIndex();
    int selectionID = Integer.parseInt(selection.replaceAll(" .*", ""));
    int selectionCount = Integer.parseInt(selection.replaceAll(".*\\[|\\ .*", ""));
    //afairoume to proion apo thn lista
    listModelright.remove(selectionIndex);   
    //kai to product_purchase OBJ apo to kalathi
    for(int i=0;i<basket.size();i++)
    {   
    //epidi sthn paragelia mporei na yparxei to idio proion me diaforetikh posothta
    //ginetai o sxetikos elegxos prin thn afairesh toy    
    if(basket.get(i).getProductId().getProductId()== selectionID && basket.get(i).getQuantity() == selectionCount)
    {
        points = points - basket.get(i).getProductId().getPoints()*basket.get(i).getQuantity();
        totalprice = totalprice - basket.get(i).getProductId().getPrice()*basket.get(i).getQuantity();
        basket.remove(i);
        i--;
    }
    }    
    //An exei xrhsimopoihthei epitagh pernoume proidopoihsh, 
    //h xrhsh epitaghs einai revesable mono me olikh akyrwsh paragelias
    if(totalprice<0){
      JOptionPane.showMessageDialog(this,"Προσοχή, Το συνολικό κόστος είναι μικρότερο απο το ποσο των επιταγών που έχετε χρησιμοποιήσει");
    //apainergopoihsh oloklhrwshs agorwn logo ths epitaghs
    btnCompleteBuy.setEnabled(false);}   
    jTxtfBuyTotal.setText(""+totalprice); //enhmervsh toy posou 
    jTxtfPurchasePoints.setText(""+points); //enhmerwsh pontwn
    //an exei adiasei to kalathi o pelaths mporei na epileksei allo katasthma
    if (listModelright.isEmpty())
    {
    jComboBoxStores.setEnabled(true); 
    }
    }//GEN-LAST:event_btnRemoveBasketProductActionPerformed
    }
    
    
    
    //Event Handler oloklhrwshs agorwn
    private void btnCompleteBuyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCompleteBuyActionPerformed
     PaymentForm pf = new PaymentForm();  //instanciate formas plhrwmhs 
     //topothetoume ta stoixeia sthn forma plhrwmhs
     pf.setTotal(totalprice);             
     pf.setCustomer(customerID);
     pf.updateFields();
     //kai thn efanizoume [edw tha peksei modality ara mexri to
     //klisimo ths formas paush ths ekteleshs]
     pf.setVisible(true);
     //to shmeio epistrofhs apo to payment form, enhmerwnoume ena Obj
     //purchase me ta katalhla stoixeia
     purchase.setPointsEarned(points);
     purchase.setCustomer(ctrl.findCustomerByCard(customerID));
     purchase.setStore(strctrl.getStore(clearStore));
     purchase.setAmount(totalprice);
     purchase.setDatetime(Calendar.getInstance().getTime());
     purchase.setProductPurchaseList(basket);
     purchase.setDelivery(jRadioButtonDelivery.isSelected());
    //Enhmerwsh Vashs me Agora efoson h plhrwmh (apo thn payment form) htan
     //eggyrh
     if(pf.validation())  
    {   
        BuyControler bc = new BuyControler();   //xrhsh tou voithitikou buyControler
        bc.addPurchase(purchase);   //adding with cascade!!!! Auto-mode ftw!!!!! :)
        ChecksControler cc = new ChecksControler();  //kai xrhsh voithitikou checks controler
        for(int i=0;i<checks2remove.size();i++)   //voiding used checks
            {
            cc.disableDefinedCheck(checks2remove.get(i));
            }   
        while(points>=200)   //prosthiki Checks
            {
            cc.addCheck(purchase.getCustomer());
            points = points-200;  //ypologismos ypoloipwn pontwn
            }
        bc.addPoints(purchase.getCustomer(), points); //prosthiki pointwn
        JOptionPane.showMessageDialog(this,"Η παραγγελία σας εχει δωθεί\n Σας Ευχαριστούμε");
        //GC sthn paymentForm
        pf.dispose();
        //epistrofh se LoginScreen
        LoginForm ls = new LoginForm();
        ls.setVisible(true);
        //GC se ayth thn forma
        this.dispose();
    }
     else  //an h Plhrwmh apetyxe
    {
        JOptionPane.showMessageDialog(this,"Η παραγγελία σας ακυρώθηκε");
        pf.dispose(); //GC sthn PaymentForm
        //katharismos ths agoras
        this.basket.clear();
        this.listModelright.removeAllElements();
        this.jTxtfBuyTotal.setText("0");
        this.jTxtfPurchasePoints.setText("0");
        jComboBoxStores.setEnabled(true);
        points=0;
        totalprice=0;
        basket.clear();
    } 
    }//GEN-LAST:event_btnCompleteBuyActionPerformed

    //Evt handler koumpi eksodou apo thn form agoras kai epistrofh se login screen
    private void btnBuyExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuyExitActionPerformed
    LoginForm ls = new LoginForm();
    ls.setVisible(true);
    this.dispose();
    }//GEN-LAST:event_btnBuyExitActionPerformed

    //Event Handler epiloghs katasthmatos apo to jComboBox
    private void jComboBoxStoresActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxStoresActionPerformed
    //katharismos twn proiontwn
    listModelleft.clear();
    //lista proiontwn
    List<Product> productList;
    int i=0;
    //an to antikeimeno tou ComboBox den einai null
    if(jComboBoxStores.getSelectedItem()!=null)
    {
    //pernoume thn perigrafh toy katasthmatos
    String dirtyStore = (String)jComboBoxStores.getSelectedItem();
    //kai eksagoume to ID [...crude??? ...yparxei eksighsh]
    clearStore = dirtyStore.replaceAll(" .*", "");
    //xrhsh voithitikou StoreControler gia fetch proiontwn apo to epilegmeno katasthma
    productList = strctrl.getStoreProducts(clearStore);
    //kai add twn proiontwn toy epilegmenou katasthmatos sthn Jlist
    for(Product product : productList){
    listModelleft.addElement(product.getProductId() + " - " + product.getName() +"     Τιμή: "+ product.getPrice());
    i++;
    }
    }
    }//GEN-LAST:event_jComboBoxStoresActionPerformed

    private void jComboBoxStoresFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jComboBoxStoresFocusGained
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBoxStoresFocusGained

    //Event Handler gia adiasma kalathiou
    private void btnEmptyBasketActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEmptyBasketActionPerformed
    //katharismos olwn twn stoixeiwn ths formas kai toy kalathiou
    listModelright.clear();
    basket.clear();
    jComboBoxStores.setEnabled(true);
    totalprice=0;
    points=0;
    jTxtfBuyTotal.setText("0");
    jTxtfPurchasePoints.setText("0");
    }//GEN-LAST:event_btnEmptyBasketActionPerformed

    //Event Handler ths epiloghs mia epitaghs
    private void useCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_useCheckActionPerformed
    //An exei epilexthei mia epitagh apo to jTable epitagwn
    if(jTable2.getSelectedRowCount()!=0){
    //pernoume to ID tis epitaghs
    int checkid = Integer.parseInt(checklistmodel.getValueAt(jTable2.getSelectedRow(), 0).toString());
    //elegxoume an to poso twn agorwn einai iso h megalytero apo thn aksia ths epitaghs
    if(totalprice>=6)
    {
    //afairoume thn epitagh apo to jTable
    checklistmodel.removeRow(jTable2.getSelectedRow());
    //enhmerwnoume to poso agorwn
    totalprice = totalprice-6;
    jTxtfBuyTotal.setText(""+totalprice);
    //kai prosthetoume thn epitagh sthn lista pros afairesh
    checks2remove.add(checkid);
    //kanoume disable to button adeiasma kalathiou (alliws tha exoume arnhtiko poso)
    btnEmptyBasket.setEnabled(false);
    }
    else
    //an to poso twn agorwn einai mikrotero apo thn aksia epitaghs eidopoioume ton xrhsth
    JOptionPane.showMessageDialog(this, "Πρέπει το υπόλοιπο ποσο αγορών να είναι τουλάχιστον 6 Ευρώ");
    }//GEN-LAST:event_useCheckActionPerformed
    }

    
    
//ena public method ths formas wste na thn enhmerwsoume kata thn dimiourfia ths
//gia ton pelath, ta diathesima katasthmata, kai arxika ta diathesima proionta    
public void setCustomerID(String cid)
{
String stoname="";
int stoID;
customerID=cid;
List<Store> storeList = strctrl.getStoreList();
jComboBoxStores.removeAllItems();
for (Store store : storeList){
jComboBoxStores.addItem(store.getStoreId().toString() + " " + store.getName().toString());
}
}    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BuyProductsScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BuyProductsScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BuyProductsScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BuyProductsScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new BuyProductsScreen().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddProduct;
    private javax.swing.JButton btnBuyExit;
    private javax.swing.JButton btnCompleteBuy;
    private javax.swing.JButton btnEmptyBasket;
    private javax.swing.JButton btnRemoveBasketProduct;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JComboBox jComboBoxStores;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JList jListAvailableProducts;
    private javax.swing.JList jListBasket;
    private javax.swing.JRadioButton jRadioButtonDelivery;
    private javax.swing.JRadioButton jRadioButtonPickup;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSpinner jSpinnerProductNum;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTxtfBuyTotal;
    private javax.swing.JTextField jTxtfPurchasePoints;
    private javax.swing.JButton useCheck;
    // End of variables declaration//GEN-END:variables
}
